package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.user.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> getBySubject(Integer subject) {
        List<Course> list = courseMapper.selectBySubject(subject);
        return list;
    }

    @Override
    public List<Course> getAll() {
        List<Course> courses = courseMapper.selectAll();
        return courses;
    }

    @Override
    public void update(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.update(course);
    }

    @Override
    public Course getById(Integer id) {
        Course course = courseMapper.selectById(id);
        return course;
    }

    @Override
    public void add(Course course) {
        //参数校验
        boolean hasNull = BeanUtil.hasNullField(course, "id","description", "createTime", "updateTime");
        if (hasNull){
            throw new RuntimeException("参数错误");
        }
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());

        courseMapper.insert(course);
    }

    @Override
    public void deleteById(Integer id) {
        courseMapper.deleteById(id);
    }

    @Override
    public PageResult<Course> list(CourseDTO dto) {

        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        List<Course> courses = courseMapper.selectByPage(dto);
        //Page对象包含总记录数是因为PageHelper在背后执行了两次查询
        // 在日志中你会看到两条SQL：
        // 1. SELECT count(0) FROM course ... (获取total)
        // 2. SELECT * FROM course LIMIT ... (获取当前页数据)

        Page<Course> page = (Page<Course>) courses;

        return PageResult.<Course>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
